#!/bin/env python
# -*- coding: utf-8 -*-

import configparser
import apilib.dnspod as dnspod
from datetime import datetime
import apilib.encryption as encryption

#读取配置
conf = configparser.ConfigParser()
conf.read("config.ini")

#处理用户名和密码
username = encryption.de(conf["auth"]["username"])
password = encryption.de(conf["auth"]["password"])

#输出当前时间
time_now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(u"当前时间：%s" % time_now)

#获取上次IP记录
try:
    fp = open("./data/last_ip.txt", "r")
    last_ip = fp.readline();
    fp.close()
    print(last_ip)
except FileNotFoundError:
    last_ip = ""
except Exception as e:
    print(e)

try:
    #获取当前DNS记录
    dnspod_api = dnspod.Dnspod(username, password)
    ret = dnspod_api.monitor_listsubvalue(conf["dns"]["domain"], conf["dns"]["record"])
    record = ret["records"][0];
    print(u"当前DNS记录\t%s" % (record["value"]))

    #根据情况更新或忽略操作
    if(last_ip == record["value"]) :
        print(u"IGNORE")
    else :
        print(u"UPDATE")
        #更新DDNS
        ret_ddns = dnspod_api.record_ddns( \
            ret["domain"]["id"], record["id"], conf["dns"]["record"], u"默认")

        #记录value
        fp = open("./data/last_ip.txt", "w")
        fp.write(ret_ddns["record"]["value"])
        fp.close()

        print("%s (%s)" % (ret_ddns["status"]["message"], ret_ddns["record"]["value"]))
except dnspod.DnspodRetException as e:
    print(str(e))

